package com.wanmait.spacesys.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.wanmait.spacesys.util.DbHelper;
import com.wanmait.spacesys.vo.Collection;
import com.wanmait.spacesys.vo.Post;
import com.wanmait.spacesys.vo.Userinfo;

/**
 * 点赞数量:数据持久化层(帖子)
 * @author 28298
 *
 */
public class PostNumberLikesDAO {
	private PostNumberLikesDAO() {}
	private static PostNumberLikesDAO postNumberLikesDAO=new PostNumberLikesDAO();
	public static PostNumberLikesDAO getPostNumberLikesDAO()
	{
		return postNumberLikesDAO;
	}
		
	//根据用户id获得帖子内容
	public List<Post> findAllPostUserinfo(Integer userinfoId,int pageNum) {
		List<Post> posts=new ArrayList<Post>();
		Connection connection=DbHelper.getConnection();
		PreparedStatement preparedStatement=null;
		ResultSet resultSet=null;
		String sql="SELECT post.id,post.title,post.content,post.praised,userinfo.id FROM post LEFT JOIN userinfo ON userinfo_id=userinfo.id WHERE userinfo.id=? and post.enable=1 "
				 + "limit "+(pageNum-1)*2+",2";
				
		try {
			preparedStatement=connection.prepareStatement(sql);
			preparedStatement.setInt(1, userinfoId);
			resultSet=preparedStatement.executeQuery();
			while(resultSet.next()) {
				Post post=new Post();
				post.setId(resultSet.getInt("id"));
				post.setTitle(resultSet.getString("title"));
				post.setContent(resultSet.getString("content"));
				post.setPraised(resultSet.getInt("praised"));
				Userinfo userinfo=new Userinfo();
				userinfo.setId(resultSet.getInt("id"));
				post.setUserinfo(userinfo);	
				posts.add(post);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			DbHelper.close(resultSet, preparedStatement, connection);
		}
		return posts;
	}
	
	//通过用户id统计点赞总数
  	public int getCount(Integer userinfoId) {
		int count = 0;
		String sql = "SELECT COUNT(post.id) FROM post WHERE userinfo_id=? and post.enable=1";
		Connection connection = DbHelper.getConnection();
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		try {
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setInt(1, userinfoId);
			resultSet = preparedStatement.executeQuery();
			if(resultSet.next()) {
				count = resultSet.getInt(1);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			DbHelper.close(resultSet,preparedStatement,connection);
		}
		return count;
		
	}
   
	//假删除帖子
	public void deletePost(Integer postId) {
		String sql="UPDATE post SET ENABLE=FALSE WHERE id=?";
		DbHelper.update(sql, postId);	
		}
	
	
	
	

	
}
